package com.aaa.ssm.config;

import com.aaa.ssm.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理所有不可知异常
     *
     * @param e 异常
     * @return json结果
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        // 打印异常堆栈信息
        log.error(e.getMessage(), e);
        return AjaxResult.defeated(e.getMessage());
    }

    /**
     * 处理所有业务异常
     *
     * @return json结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult validationBodyException(MethodArgumentNotValidException exception) {
        AjaxResult AjaxResult = printMessage(exception);
        return AjaxResult;
    }

    @ExceptionHandler(BindException.class)
    public AjaxResult validationBodyException(BindException exception) {
        AjaxResult AjaxResult = printMessage(exception);
        return AjaxResult;
    }


    private   AjaxResult   printMessage(BindException  e){

        BindingResult result =    e.getBindingResult();
        String message = "";
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            if (errors != null) {

                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    log.error("Data check failure : object{" + fieldError.getObjectName() + "},field{" + fieldError.getField() +
                            "},errorMessage{" + fieldError.getDefaultMessage() + "}");

                });

                if (errors.size() > 0) {
                    FieldError fieldError = (FieldError) errors.get(0);
                    message = fieldError.getDefaultMessage();
                }
            }
        }

        String s = "".equals(message) ? "请填写正确信息" : message;

        return AjaxResult.defeated(s);
    }

}